#include "stdafx.h"
#include <time.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include "shlwapi.h"
#include "shlobj.h"
#include "LogFile.h"
#include "log.h"
#include "multi_log.h"
#include "str.h"
using namespace std;

#pragma comment( lib, "shlwapi.lib" )
#pragma comment( lib, "ws2_32.lib" )

namespace Zen{namespace utility{

map<string, simple_log*> multi_log::logs;

void multi_log::operator()( char* fmt, ... )
{
	char str[1024];
	int size;

	va_list args;
	va_start(args, fmt);
	size = _vsnprintf_s(str, sizeof(str), fmt, args);
	va_end(args);

	if (logs[name_]->GetLogFile() != NULL)
		logs[name_]->GetLogFile()->log(str);

	printf("[%s] %s\r\n", name_.c_str(), str);

	if (logs[name_]->GetLogSize() >= LOG_MAX_SIZE) 
	{
		//PrintLog("current log file size: %d large than %d, (%s)\n", GetLogSize(), LOG_MAX_SIZE, GetLogName());
		logs[name_]->CloseLog();
		logs[name_]->OpenLog();
		(*(this))("create new log file(%s)\n", logs[name_]->GetLogName());
	}

}

void multi_log::operator()( wchar_t* fmt, ... )
{
	wchar_t str[1024];
	int size;

	va_list args;
	va_start(args, fmt);
	size = _vsnwprintf_s(str, sizeof(str), fmt, args);
	va_end(args);

	string msg = ws2s(str);

	if (logs[name_]->GetLogFile() != NULL)
		logs[name_]->GetLogFile()->log(msg.c_str());

	printf("[%s] %s\r\n", name_.c_str(), msg.c_str());

	if (logs[name_]->GetLogSize() >= LOG_MAX_SIZE) 
	{
		//PrintLog("current log file size: %d large than %d, (%s)\n", GetLogSize(), LOG_MAX_SIZE, GetLogName());
		logs[name_]->CloseLog();
		logs[name_]->OpenLog();
		(*(this))("create new log file(%s)\n", logs[name_]->GetLogName());
	}

}

multi_log::multi_log( string name )
	:name_(name)
{
	if (logs.end() == logs.find(name))
	{
		logs[name] = new simple_log(name);
	}
}

multi_log::~multi_log()
{

}

void close_log()
{
	for (map<string, simple_log*>::iterator it = multi_log::logs.begin(); it != multi_log::logs.end(); it++)
	{
		delete it->second;
	}
}

}}
